package com.example.mypotiota_si.Activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.example.mypotiota_si.Adapter.ListViewAdapter_bz;
import com.example.mypotiota_si.Adapter.ListViewAdapter_xx;
import com.example.mypotiota_si.Adapter.LooperPagerAdapter;
import com.example.mypotiota_si.Adapter.StaggerAdapter_sy_dp;
import com.example.mypotiota_si.Adapter.ViewpagerAdapter;
import com.example.mypotiota_si.Datas.BangZhu_nr;
import com.example.mypotiota_si.Datas.Bangzhu;
import com.example.mypotiota_si.Datas.Dianpu;
import com.example.mypotiota_si.Datas.Dianpu_nr;
import com.example.mypotiota_si.Datas.MainActivity_Shop_date;
import com.example.mypotiota_si.Datas.Xiaoxi;
import com.example.mypotiota_si.Datas.Xiaoxi_nr;
import com.example.mypotiota_si.Initainalper.InitenActivity;
import com.example.mypotiota_si.Pager.MyViewPager;
import com.example.mypotiota_si.R;
import com.example.mypotiota_si.Tool.Tools;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends InitenActivity implements ViewPager.OnPageChangeListener, MyViewPager.OnViewPagerTouchListener {
    private static final String TAG = "MainActivity";
    //首页
    LinearLayout sy_title_xx,sy_title_ss;
    RecyclerView sy_dp_recyclerView;
    private ArrayList<Dianpu> dianpu=new ArrayList<>();
    private StaggerAdapter_sy_dp sy_dp_adapter;
    LinearLayout shou_ye_wm,shou_ye_fl,shou_ye_pm;
    //轮播图
    private MyViewPager looper_pager;
    private LooperPagerAdapter looperPagerAdapter;
    private static List<Integer> sPics=new ArrayList<>();
    static {
        sPics.add(R.mipmap.emei_looper1);
        sPics.add(R.mipmap.emei_looper2);
        sPics.add(R.mipmap.emei_looper3);
    }
    private Handler mHandler;
    //添加标记量
    private boolean mIsTouch=false;
    LinearLayout pointContainer;

    //消息
    RecyclerView xx_listView;
    private ArrayList<Xiaoxi> xiaoxi=new ArrayList<>();
    private ListViewAdapter_xx xx_adapter;
    //帮助
    RecyclerView bz_listView;
    private ArrayList<Bangzhu> bangzhu=new ArrayList<>();
    private ListViewAdapter_bz bz_adapter;
    //我的
    LinearLayout wd_tc;
    private Button wd_dj_dz,wd_dj_dd,wd_dj_sc,wd_dj_zj,wd_dj_gy;

    ViewPager viewPager;
    BottomNavigationBar bottomNavigationBar;
    private LayoutInflater inflater;
    private List<View> viewList;
    private View view1;
    private View view2;
    private View view3;
    private View view4;
    private String str;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private ArrayList<MainActivity_Shop_date> shop_dates;
    private MainActivity_Shop_date mainActivity_shop_date;
    private ArrayList<String> strings;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //隐藏标题栏
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.hide();
        }
        sharedPreferences = getSharedPreferences("shop",MODE_PRIVATE);
        editor = sharedPreferences.edit();




        //
//        try {
//            InputStream is = getResources().openRawResource(R.raw.dates);
//            InputStreamReader isr = new InputStreamReader(is,"UTF-8");
//            BufferedReader br = new BufferedReader(isr);
//            str = "";
//            while((str = br.readLine()) != null){
//                Log.i(TAG, "onCreate: "+str.trim());
//                editor.putString("str",str);
//                editor.commit();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        Log.i(TAG, "onCreate: "+Tools.getJson("json.json",MainActivity.this));


        //找到控件主页面
        viewPager=findViewById(R.id.view_pager);
        bottomNavigationBar=findViewById(R.id.bottom_navigation_bar);
        //添加页面
        viewList=new ArrayList<>();
        inflater=getLayoutInflater();
        view1=inflater.inflate(R.layout.activity_shou_ye,null,false);
        view2=inflater.inflate(R.layout.activity_bang_zhu,null,false);
        view3=inflater.inflate(R.layout.activity_xiao_xi,null,false);
        view4=inflater.inflate(R.layout.activity_wo_de,null,false);
        viewList.add(view1);
        viewList.add(view2);
        viewList.add(view3);
        viewList.add(view4);

        //找到子页面控件
        pointContainer=view1.findViewById(R.id.points_container);
        shou_ye_wm=view1.findViewById(R.id.shou_ye_wm);
        shou_ye_fl=view1.findViewById(R.id.shou_ye_fl);
        shou_ye_pm=view1.findViewById(R.id.shou_ye_pm);
        sy_title_xx=view1.findViewById(R.id.title_xx);
        sy_title_ss=view1.findViewById(R.id.title_ss);
        sy_dp_recyclerView=view1.findViewById(R.id.recycler_sy_view);
        bz_listView=view2.findViewById(R.id.recycler_bz_view);
        xx_listView=view3.findViewById(R.id.recycler_xx_view);
        wd_tc=view4.findViewById(R.id.wd_tc);
        wd_dj_dz=view4.findViewById(R.id.wd_dj_dz);
        wd_dj_dd=view4.findViewById(R.id.wd_dj_dd);
        wd_dj_sc=view4.findViewById(R.id.wd_dj_sc);
//        wd_dj_zj=view4.findViewById(R.id.wd_dj_zj);
        wd_dj_gy=view4.findViewById(R.id.wd_dj_gy);


        ViewpagerAdapter viewpagerAdapter=new ViewpagerAdapter(MainActivity.this,viewList);
        viewPager.setAdapter(viewpagerAdapter);

        //添加按键元素
        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.drawable.emei_dh_sy,"首页"))
                .addItem(new BottomNavigationItem(R.drawable.emei_dh_bz,"帮助"))
                .addItem(new BottomNavigationItem(R.drawable.emei_dh_xx,"消息"))
                .addItem(new BottomNavigationItem(R.drawable.emei_dh_wd,"我的"))
                .initialise();//所有设置在调用该方法前完成
        //给viewpager添加滑动事件
        init_hd();
        //BottomNavigationBar的点击事件
        init_dj();
        //每个页面添加数据
        initDatas_sy();
        initDatas_xx();
        initDatas_bz();
        //设置样式每个页面
        init_ys();

    }

    private String readTextFromSDcard(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is, "GB2312");
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }
        return buffer.toString();//把读取的数据返回
    }

        //设置样式每个页面
    private void init_ys() {
        //设置样式--首页
        //首页--店铺


        //拿文件内的店铺

        String date= Tools.getJson("json.json",MainActivity.this);
        shop_dates = new ArrayList<>();
        try {
            JSONObject jsonObject=new JSONObject(date);
            JSONArray jsonArray=jsonObject.getJSONArray("shop_dates");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1=jsonArray.getJSONObject(i);
                JSONArray date1=jsonObject1.getJSONArray("date");
                for (int i1 = 0; i1 < date1.length(); i1++) {
                    JSONObject shop=date1.getJSONObject(i1);

                    mainActivity_shop_date = new MainActivity_Shop_date();
                    String shop_name=shop.getString("shop_name");//商铺名称
                    String shop_image_address=shop.getString("shop_image_address");//图片
                    String heart=shop.getString("shop_heart");//评分
                    //获取月售
                    String shop_yuehsou=shop.getString("shop_yuehsou");
                    String shop_address_s=shop.getString("shop_address");
                    String shop_address=shop.getString("shop_image_address");
                    String shop_Delivery_time=shop.getString("shop_Delivery_time");
                    String shop_qisong=shop.getString("shop_qisong");
                    String shop_gonggao=shop.getString("shop_gonggao");
                    String shop_peisongfei=shop.getString("shop_peisongfei");
                    JSONArray jsonArray1=shop.getJSONArray("shop_date");

                    mainActivity_shop_date.setShop_address(shop_address_s);
                    mainActivity_shop_date.setShop_Delivery_time(shop_Delivery_time);
                    mainActivity_shop_date.setShop_qisong(shop_qisong);
                    mainActivity_shop_date.setShop_gonggao(shop_gonggao);
                    mainActivity_shop_date.setShop_peisongfei(shop_peisongfei);
                    mainActivity_shop_date.setDates(jsonArray1+"");
                    mainActivity_shop_date.setName(shop_name);
                    mainActivity_shop_date.setHeart(heart);
                    mainActivity_shop_date.setAddress(shop_image_address);
                    mainActivity_shop_date.setYueshou(shop_yuehsou);
                    shop_dates.add(mainActivity_shop_date);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }





        StaggeredGridLayoutManager layoutManager_sy=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        sy_dp_recyclerView.setLayoutManager(layoutManager_sy);
        sy_dp_adapter=new StaggerAdapter_sy_dp(strings,shop_dates,MainActivity.this);
        sy_dp_recyclerView.setAdapter(sy_dp_adapter);
        //首页点击事件
        init_dj_sy();

        //设置样式--消息
        LinearLayoutManager layoutManager_xx=new LinearLayoutManager(this);
        xx_listView.setLayoutManager(layoutManager_xx);
        xx_adapter=new ListViewAdapter_xx(xiaoxi,MainActivity.this);
        xx_listView.setAdapter(xx_adapter);
        //设置样式--帮助
        LinearLayoutManager layoutManager_bz=new LinearLayoutManager(this);
        bz_listView.setLayoutManager(layoutManager_bz);
        bz_adapter=new ListViewAdapter_bz(bangzhu);
        bz_listView.setAdapter(bz_adapter);

        //我的点击事件
        init_dj_wd();
    }
    //我的点击事件
    private void init_dj_wd() {
        //点击退出
        wd_tc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,DengLuActivity.class);
                startActivity(intent);
            }
        });
        //点击地址
        wd_dj_dz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,WoDe_DiZhiActivity.class);
                startActivity(intent);
            }
        });
        //点击订单
        wd_dj_dd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,WoDe_DingDanActivity.class);
                startActivity(intent);
            }
        });
        //点击收藏
        wd_dj_sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,WoDe_ShouCangActivity.class);
                startActivity(intent);
            }
        });
        //点击足迹
//        wd_dj_zj.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent=new Intent(MainActivity.this,WoDe_ZuJiActivity.class);
//                startActivity(intent);
//            }
//        });
        //点击关于
        wd_dj_gy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,WoDe_SheZhiActivity.class);
                startActivity(intent);
            }
        });
    }

    //首页点击事件
    private void init_dj_sy() {
        //点击学校
        sy_title_xx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this, ShouYe_SchoolActivity.class);
                startActivity(intent);
            }
        });
        //点击搜索
        sy_title_ss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,SouSuoActivity.class);
                startActivity(intent);
            }
        });
        //点击外卖
        shou_ye_wm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,WaiMaiActivity.class);
                startActivity(intent);
            }
        });
        //点击分类
        shou_ye_fl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,FenLeiActivity.class);
                startActivity(intent);
            }
        });
        //点击排名
        shou_ye_pm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,PaiMingActivity.class);
                startActivity(intent);
            }
        });
    }

    //BottomNavigationBar的点击事件
    private void init_dj() {
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
           //选择时调用
            @Override
            public void onTabSelected(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });

    }

    //给viewpager添加滑动事件
    private void init_hd() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
//新页面调动时调用该方法
            @Override
            public void onPageSelected(int position) {
                bottomNavigationBar.selectTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //首页添加数据
    private void initDatas_sy() {
        //添加轮播器
        looper_pager=view1.findViewById(R.id.looper_pager);
        looperPagerAdapter=new LooperPagerAdapter();
        looperPagerAdapter.setData(sPics);
        looper_pager.setAdapter(looperPagerAdapter);
        looper_pager.setOnViewPagerTouchListener(this);
        looper_pager.addOnPageChangeListener(this);

        //根据图片个数添加点的个数
        insertPoint();
        //往前滑动（保持第一张开始）
        looper_pager.setCurrentItem(looperPagerAdapter.getDataRealSize()*100,false);
        mHandler=new Handler();

        //添加店铺数据
        dianpu=new ArrayList<>();
        for (int i = 0; i < Dianpu_nr.icon.length; i++) {
            Dianpu dp=new Dianpu();
            dp.dp_icon=Dianpu_nr.icon[i];
            dp.dp_name=Dianpu_nr.name[i];
            dp.dp_pf=Dianpu_nr.pf[i];
            dp.dp_ys=Dianpu_nr.ys[i];
            dianpu.add(dp);
        }
    }
    //消息添加数据
    private void initDatas_xx() {
        xiaoxi=new ArrayList<>();
        for (int i = 0; i < Xiaoxi_nr.icon.length; i++) {
            Xiaoxi xx=new Xiaoxi();
            xx.xx_icon=Xiaoxi_nr.icon[i];
            xx.xx_name=Xiaoxi_nr.name[i];
            xx.xx_nr=Xiaoxi_nr.nr[i];
            xiaoxi.add(xx);
        }
    }
    //帮助添加数据
    private void initDatas_bz() {
        bangzhu=new ArrayList<>();
        for (int i = 0; i < BangZhu_nr.icon.length; i++) {
            Bangzhu bz=new Bangzhu();
            bz.bz_icon=BangZhu_nr.icon[i];
            bz.bz_nr=BangZhu_nr.nr[i];
            bangzhu.add(bz);
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        //当我的界面绑定到我的界面
        mHandler.post(mLooperTask);
    }
    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mHandler.removeCallbacks(mLooperTask);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private Runnable mLooperTask=new Runnable() {
        @Override
        public void run() {
            if (!mIsTouch){
                //切换viewPager的图片到下一个
                int currentIte=looper_pager.getCurrentItem();
                looper_pager.setCurrentItem(++currentIte,false);
            }
            mHandler.postDelayed(this,3000);
        }
    };

    //根据图片个数添加点的个数
    private void insertPoint() {
        for (int i = 0; i < sPics.size(); i++) {
//            Log.i(TAG,sPics.size()+"");
            View point=new View(this);
            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(30,30);
            point.setBackground(getResources().getDrawable(R.drawable.shape_point_normal));
            layoutParams.leftMargin=20;
            point.setLayoutParams(layoutParams);
            pointContainer.addView(point);
        }
    }

    @Override
    public void onPagerTouch(boolean isTouch) {
        mIsTouch=isTouch;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
//viewPager停下来的时候选中的位置
        int realPosition;
        if (looperPagerAdapter.getDataRealSize()!=0){
            realPosition=position%looperPagerAdapter.getDataRealSize();
        }else {
            realPosition=0;
        }
        setSelectPoint(realPosition);
    }
    public void setSelectPoint(int realPosition) {
        for (int i = 0; i < pointContainer.getChildCount(); i++) {
            View point=pointContainer.getChildAt(i);
            if (i!=realPosition){
                //那就是白色
                point.setBackgroundResource(R.drawable.shape_point_normal);
            }else {
                //选中颜色
                point.setBackgroundResource(R.drawable.shape_point_selected);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
